import {ScrollTypes} from '../types'

/**
 * 
 * @param id 滚动盒子id
 * @param emit 滚动触发事件
 * @param direction 滚动方向
 * @returns 
 */
export function useScroll(id: string, emit:ScrollTypes.EmitSign, direction: ScrollTypes.ScrollDirection) {
  const scrollBox = shallowRef<HTMLElement | null>(null)
  const topOrLeft = ref<number>(0) // 滚动条滚动距离，纵向滚动时为距离顶部距离，横向滚动时，为距离左方距离
  const clientHeightOrClientWidth = ref<number>(0) // 可视区域高度或者宽度
  const scrollHeightOrscrollWidth = ref<number>(0) // 内容区域高度或者宽度， 包括不可见的滚动区域
  
  const bottomOrRight = computed(() => {
    return scrollHeightOrscrollWidth.value - clientHeightOrClientWidth.value - topOrLeft.value
  })

  const listenScroll = (e: Event) => {
    const target = e.target as HTMLDivElement
    const {scrollTop, scrollLeft, clientHeight, clientWidth, scrollHeight, scrollWidth} = target
    
    topOrLeft.value = direction === 'y' ? scrollTop : scrollLeft
    clientHeightOrClientWidth.value = direction === 'y' ? clientHeight : clientWidth
    scrollHeightOrscrollWidth.value = direction === 'y' ? scrollHeight : scrollWidth

    // 滚动通知, 同时暴露滚动条距离top和bottom的距离，或者left和right的距离
    emit('scrolling', {topOrLeft: topOrLeft.value, bottomOrRight: bottomOrRight.value})

    const addScrollAndClientHeight = topOrLeft.value + clientHeightOrClientWidth.value

    if (addScrollAndClientHeight === scrollHeightOrscrollWidth.value) {
      emit('touchBottomOrRight') // 触底通知
    }
  }

  const createListener = () => {
    scrollBox.value = document.getElementById(id) as HTMLElement
    scrollBox.value.addEventListener('scroll', listenScroll)
  }

  onMounted(createListener)

  return {
    scrollBox,
    topOrLeft,
    bottomOrRight
  }
}
